package com.xinshujia.service.impl;

import com.xinshujia.dao.QuartzDao;
import com.xinshujia.entity.QuartzEntity;
import com.xinshujia.service.QuartzService;
import com.xinshujia.utils.ConstantsUtil;
import org.quartz.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-23 14:48       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 */
@Service
public class QuartzServiceImpl implements QuartzService {
    private final QuartzDao quartzDao;

    public QuartzServiceImpl(QuartzDao quartzDao) {
        this.quartzDao = quartzDao;
    }

    /**
     * 创建任务
     */
    @Override
    public boolean createJob(Scheduler scheduler, QuartzEntity quartzEntity) throws RuntimeException {
        try {
            // 执行一次删除定时任务的操作
            deleteJob(scheduler, quartzEntity.getJobName());

            //定时任务类需要是job类的具体实现 QuartzJobBean是job的抽象类。
            Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(quartzEntity.getJobClass());
            // 构建定时任务信息
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(quartzEntity.getJobName()).build();
            // 设置定时任务执行方式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzEntity.getCron());
            // 构建触发器trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(quartzEntity.getJobName()).withSchedule(scheduleBuilder).build();
            Date date = scheduler.scheduleJob(jobDetail, trigger);
            if (date != null){
                quartzEntity.setStatus(ConstantsUtil.QUARTZ_STATUS_RUNNING);
                QuartzEntity entity = quartzDao.saveAndFlush(quartzEntity);
                if(!ObjectUtils.isEmpty(entity)){
                    return true;
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("定时任务类路径出错：请输入类的绝对路径");
        } catch (SchedulerException e) {
           throw new RuntimeException("创建定时任务出错：" + e.getMessage());
        }
        return false;
    }

    /**
     * 暂停任务
     */
    @Override
    public boolean pauseJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.pauseJob(jobKey);
            QuartzEntity quartzEntity = getQuartzByJobName(jobName);
            if (!ObjectUtils.isEmpty(quartzEntity)){
                quartzEntity.setStatus(ConstantsUtil.QUARTZ_STATUS_STOP);
                QuartzEntity entity = quartzDao.saveAndFlush(quartzEntity);
                if(!ObjectUtils.isEmpty(entity)){
                    return true;
                }
            }
        } catch (SchedulerException e) {
            throw new RuntimeException("暂停定时任务出错：" + e.getMessage());
        }
        return false;
    }

    /**
     * 恢复任务
     */
    @Override
    public boolean resumeJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.resumeJob(jobKey);
            QuartzEntity quartzEntity = getQuartzByJobName(jobName);
            if (!ObjectUtils.isEmpty(quartzEntity)){
                quartzEntity.setStatus(ConstantsUtil.QUARTZ_STATUS_RUNNING);
                QuartzEntity entity = quartzDao.saveAndFlush(quartzEntity);
                if(!ObjectUtils.isEmpty(entity)){
                    return true;
                }
            }
        } catch (SchedulerException e) {
            throw new RuntimeException("启动定时任务出错：" + e.getMessage());
        }
        return false;
    }

    /**
     * 更新任务
     */
    @Override
    public boolean updateJob(Scheduler scheduler, QuartzEntity quartzEntity) {
        try {
            //获取到对应任务的触发器
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzEntity.getJobName());
            //设置定时任务执行方式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzEntity.getCron());
            //重新构建任务的触发器trigger
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //重置对应的job
            Date date = scheduler.rescheduleJob(triggerKey, trigger);
            if (date != null){
                quartzEntity.setStatus(ConstantsUtil.QUARTZ_STATUS_RUNNING);
                QuartzEntity entity = quartzDao.saveAndFlush(quartzEntity);
                if(!ObjectUtils.isEmpty(entity)){
                    return true;
                }
            }
        } catch (SchedulerException e) {
            throw new RuntimeException("更新定时任务出错：" + e.getMessage());
        }
        return false;
    }

    /**
     * 删除任务
     */
    @Override
    public boolean deleteJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.deleteJob(jobKey);
            QuartzEntity quartzEntity = getQuartzByJobName(jobName);
            if (!ObjectUtils.isEmpty(quartzEntity)){
                quartzDao.delete(quartzEntity);
                return true;
            }
        } catch (SchedulerException e) {
            throw new RuntimeException("删除定时任务出错：" + e.getMessage());
        }
        return false;
    }


    @Override
    public QuartzEntity getQuartzByJobName(String jobName) {
        return quartzDao.getQuartzByJobName(jobName);
    }

    /**
     * 查询所有定时任务
     */
    @Override
    public List<QuartzEntity> getQuartzs() {
        return quartzDao.findAll();
    }

}
